#include "RealTimeDealStat.h"

#include <core/Utility.h>

#include "RealTimeDealUtil.h"
namespace detail {

RealTimeDealStat::RealTimeDealStat() {}
void RealTimeDealStat::AddStat(const MarketStreamInfo& info) {
  if (!CheckIndexId(info.m_indexID, info.m_body.m_id)) return;
  StatType* stat = GetOrCreate(info);
  if (stat) {
    MSUtil::CaculateRecordPrice(*stat, info);
  }
  /*StatType stat;
  char key[128] = { 0 };
  FMTBUF(key, "%s.%s", info.m_body.m_bondkey, info.m_body.m_listedmarket);
  m_stats.insert(StatTypeMap::value_type(key, stat));*/
}
void RealTimeDealStat::AddStatMap(const RealTimeDealStat* pStatMap) {
  if (pStatMap == NULL) return;

  StatTypeMap::const_iterator it = pStatMap->m_stats.cbegin();
  for (; it != pStatMap->m_stats.cend(); ++it) {
    const MarketStreamRec& rec = it->second;
    detail::MSUtil::InsertMarketRecord(it->first.c_str(), rec, m_stats);
  }
}
void RealTimeDealStat::UpdateStat(const MarketStreamInfo& oldInfo,
                                  const MarketStreamInfo& info) {
  if (!CheckIndexId(info.m_indexID, info.m_body.m_id)) return;
  StatType* stat = GetOrCreate(info);
  if (stat) {
    MSUtil::DeletePrice(oldInfo, *stat);
    MSUtil::CaculateRecordPrice(*stat, info);
  }
}
bool RealTimeDealStat::CheckIndexId(int indexId, const char* id) {
  return true;  // 忽略去重
}
void RealTimeDealStat::EraseStat(const MarketStreamInfo& info, bool bfound) {
  if (!CheckIndexId(info.m_indexID, info.m_body.m_id)) return;
  StatType* stat = GetOrCreate(info);
  if (stat && bfound) MSUtil::DeletePrice(info, *stat);
}
bool RealTimeDealStat::GetStat(const std::string& combBondKey,
                               StatType& stat) const {
  StatTypeMap::const_iterator it = m_stats.find(combBondKey);
  if (it != m_stats.cend()) {
    stat = it->second;
    return true;
  }
  return false;
}
RealTimeDealStat::StatType* RealTimeDealStat::GetOrCreate(
    const MarketStreamInfo& info) {
  std::string strComKey = std::string(info.m_body.m_bondkey) +
                          std::string(".") +
                          std::string(info.m_body.m_listedmarket);
  StatTypeMap::iterator it = m_stats.find(strComKey);
  if (it == m_stats.end()) {
    StatType stRec;
    memset(&stRec, 0, sizeof(stRec));
    // FIELDCOPY(stRec.m_bondCode, info.m_body.m_bondCode);
    FIELDCOPY(stRec.m_bondkey, info.m_body.m_bondkey);
    FIELDCOPY(stRec.m_listedmarket, info.m_body.m_listedmarket);
    m_stats[strComKey] = stRec;
    it = m_stats.find(strComKey);
  }
  return &(it->second);
}
}  // namespace detail
